package org.chen.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.chen.domain.vo.CrawlerResult;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CrawlerLogUtil {
    
    private static final String LOG_DIR = "logs/crawler";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");

    static {
        try {
            Files.createDirectories(Paths.get(LOG_DIR));
        } catch (Exception e) {
            log.error("Failed to create log directory: {}", e.getMessage());
        }
    }
    
    public static void logTaskStart(String taskId, String source, Integer targetCount) {
        try {
            Map<String, Object> logEntry = new HashMap<>();
            LocalDateTime now = LocalDateTime.now();
            
            logEntry.put("timestamp", now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            logEntry.put("type", "TASK_START");
            logEntry.put("taskId", taskId);
            logEntry.put("source", source);
            logEntry.put("targetCount", targetCount);
            
            writeLogEntry(source, logEntry);
        } catch (Exception e) {
            log.error("Failed to log task start: {}", e.getMessage());
        }
    }
    
    public static void logTaskComplete(String taskId, CrawlerResult result) {
        try {
            Map<String, Object> logEntry = new HashMap<>();
            LocalDateTime now = LocalDateTime.now();
            
            logEntry.put("timestamp", now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            logEntry.put("type", "TASK_COMPLETE");
            logEntry.put("taskId", taskId);
            logEntry.put("source", result.getSource());
            logEntry.put("total", result.getTotal());
            logEntry.put("success", result.getSuccess());
            logEntry.put("failed", result.getFailed());
            logEntry.put("duration", result.getDuration());
            logEntry.put("errors", result.getErrors());
            
            writeLogEntry(result.getSource(), logEntry);
        } catch (Exception e) {
            log.error("Failed to log task complete: {}", e.getMessage());
        }
    }
    
    @SuppressWarnings("unchecked")
    private static synchronized void writeLogEntry(String source, Map<String, Object> logEntry) throws Exception {
        String today = LocalDateTime.now().format(DATE_FORMAT);
        String logFile = String.format("%s/%s_%s.json", LOG_DIR, source, today);
        File file = new File(logFile);
        
        List<Map<String, Object>> entries;
        if (file.exists()) {
            entries = objectMapper.readValue(file, List.class);
        } else {
            entries = new ArrayList<>();
        }
        
        entries.add(logEntry);
        
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(objectMapper.writeValueAsString(entries));
        }
    }
}